package apple.encryptedNode.activities;

import it.telecomitalia.jchat.R;

import java.io.File;
import java.io.IOException;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

import apple.encryptedNode.dao.EncryptedNodeOpenHelper;
import apple.encryptedNode.dao.OperationDAO;
import apple.encryptedNote.tools.EncryptTool;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/***
 * 主界面
 * 
 * **/
public class EncryptedNoteActivity extends ListActivity {
	private Cursor mCursor;
	private OperationDAO operationDAO;
	private Long firstClickTime;
	private int longSelectPosition = -1;
	private String s;
	private String s1, s2;
	String tlon = null;
	String tlai = null;
	String trrd = null;

	// private Button newNoteButton;
	private static final double Radio = 6371.004;

	public boolean IsCorrect(double lng1, double lat1, double lng2,
			double lat2, double d) {
		double c = Math.sin(lat1) * Math.sin(lat2) * Math.cos(lng1 - lng2)
				+ Math.cos(lat1) * Math.cos(lat2);
		double s = Radio * Math.acos(c) * Math.PI * 1000 / 180;
		if (s <= d)
			return true;
		else
			return false;
	}

	public static String sha1(String data) {
		try {
			byte[] b = data.getBytes();
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.reset();
			md.update(b);
			byte messageDigest[] = md.digest();
			StringBuilder result = new StringBuilder();
			for (int i = 0; i < messageDigest.length; i++) {
				result.append(Integer.toString(
						(messageDigest[i] & 0xff) + 0x100, 16).substring(1));
			}

			return result.toString();

		} catch (NoSuchAlgorithmException e) {

			// Log.e("ARTags", "SHA1 is not a supported algorithm");
		}
		return null;
	}

	// 初始化坐标
	private void loc() {
		// 获取解密密码
		LocationManager lm = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// 定义Criteria对象
		Criteria criteria = new Criteria();
		// 设置定位精确度 Criteria.ACCURACY_COARSE 比较粗略， Criteria.ACCURACY_FINE则比较精细
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		// 设置是否需要海拔信息 Altitude
		criteria.setAltitudeRequired(true);
		// 设置是否需要方位信息 Bearing
		criteria.setBearingRequired(true);
		// 设置是否允许运营商收费
		criteria.setCostAllowed(true);
		// 设置对电源的需求
		criteria.setPowerRequirement(Criteria.POWER_LOW);

		// 获取GPS信息提供者
		String bestProvider = lm.getBestProvider(criteria, true);

		// 获取定位信息
		Location location;
		location = lm.getLastKnownLocation(bestProvider);
		double longitude = 0;
		double latitude = 0;
		if (location != null) {
			longitude = (double) (location.getLongitude());
			latitude = (double) (location.getLatitude());
		}

		// 位置监听器
		LocationListener locationListener = new LocationListener() {

			// 当位置改变时触发
			public void onLocationChanged(Location location) {
				Log.i("yao", location.toString());
			}

			// Provider失效时触发
			public void onProviderDisabled(String arg0) {
				Log.i("yao", arg0);

			}

			// Provider可用时触发
			public void onProviderEnabled(String arg0) {
				Log.i("yao", arg0);
			}

			// Provider状态改变时触发
			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
				Log.i("yao", "onStatusChanged");
			}
		};
		// 500毫秒更新一次，忽略位置变化
		lm.requestLocationUpdates(bestProvider, 500, 0, locationListener);

		s1 = String.format("%.4f", longitude);
		s2 = String.format("%.4f", latitude);
		s = s1 + s2;

	}

	// 初始化List
	public void list() {
		firstClickTime = new Long(0);
		mCursor = this.operationDAO.query();
		startManagingCursor(mCursor);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
		// android.R.layout.two_line_list_item,
				R.layout.note_list_component, mCursor,
				// new String[] {People.NAME},
				new String[] { EncryptedNodeOpenHelper.KEY_NAME,
						EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
						R.id.topicName, R.id.topicContent });
		adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

			public boolean setViewValue(View view, Cursor cursor,
					int columnIndex) {
				System.out.println(view.toString());
				System.out.println("adam~" + "columnIndex:" + columnIndex
						+ ((TextView) view).getText().toString());
				return false;
			}
		});
		setListAdapter(adapter);

		adapter.notifyDataSetChanged();

		getListView().setOnItemLongClickListener(listenter);
	}

	// 监听事件
	OnItemLongClickListener listenter = new OnItemLongClickListener() {

		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			longSelectPosition = arg2;
			final CharSequence[] items = { getString(R.string.open),
					getString(R.string.delete), getString(R.string.encrypt),
					getString(R.string.decrypt), getString(R.string.send) };
			AlertDialog.Builder builder = new AlertDialog.Builder(
					EncryptedNoteActivity.this);
			builder.setTitle("Operations");
			builder.setItems(items, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int item) {
					switch (item) {
					case 0:// open
						if (longSelectPosition > -1) {
							mCursor.moveToPosition(longSelectPosition);
							int keyId = mCursor.getInt(0);
							String keyName = mCursor.getString(1);
							String keyContent = mCursor.getString(2);
							longSelectPosition = -1;
							showNewNoteActivity(keyId, keyName, keyContent);
						}
						break;
					case 1:// delete
						if (longSelectPosition > -1) {
							mCursor.moveToPosition(longSelectPosition);
							int id = mCursor.getInt(0);
							String fileName = mCursor.getString(1);
							if (fileName.contains(" *encrypted*")) {
								Log.e("adam", "Contains encrypted");
								AlertDialog.Builder builder = new AlertDialog.Builder(
										EncryptedNoteActivity.this);
								builder.setMessage(
										"Please decrypt this note first!")
										.setCancelable(false)
										.setNegativeButton(
												"Comfirm",
												new DialogInterface.OnClickListener() {
													public void onClick(
															DialogInterface dialog,
															int id) {
														dialog.cancel();
													}
												});
								AlertDialog alert = builder.create();
								alert.show();
							} else {
								longSelectPosition = -1;
								operationDAO.delete(id);
								// mCursor = operationDAO.query();
								mCursor.requery();
								startManagingCursor(mCursor);
								EncryptedNoteActivity.this.getListView()
										.clearDisappearingChildren();
							}
						}

						break;
					case 2:// encrypt
						mCursor.moveToPosition(longSelectPosition);
						// int id = mCursor.getInt(0);
						String fileName = mCursor.getString(1);
						if (fileName.contains(" *encrypted*")) {
							Log.e("adam", "Contains encrypted");
							AlertDialog.Builder builder = new AlertDialog.Builder(
									EncryptedNoteActivity.this);
							builder.setMessage(
									"This note is already encrypted!")
									.setCancelable(false)
									.setNegativeButton(
											"Comfirm",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													dialog.cancel();
												}
											});
							AlertDialog alert = builder.create();
							alert.show();
						} else {
							Dialog encryptionDialog = new Dialog(
									EncryptedNoteActivity.this);
							encryptionDialog
									.setContentView(R.layout.encryptiondialog);
							encryptionDialog.setTitle("请核对信息无误!");
							Button dialogOperateButton = (Button) encryptionDialog
									.findViewById(R.id.dialogOperateButton);
							dialogOperateButton.setText("加密");
							Button dialogCancelButton = (Button) encryptionDialog
									.findViewById(R.id.dialogCancelButton);
							dialogCancelButton
									.setOnClickListener(new DialogDismiss(
											encryptionDialog));
							dialogOperateButton
									.setOnClickListener(new DialogEncryptionBtnEvent(
											encryptionDialog));

							encryptionDialog.show();
						}
						break;
					case 3:// decrypt
						mCursor.moveToPosition(longSelectPosition);
						// int id1 = mCursor.getInt(0);
						String fileName1 = mCursor.getString(1);
						Log.e("adam",
								"fileName:" + fileName1
										+ fileName1.contains(" *encrypted*"));
						if (!fileName1.contains(" *encrypted*")) {
							Log.e("adam", "not Contains encrypted");
							AlertDialog.Builder builder = new AlertDialog.Builder(
									EncryptedNoteActivity.this);
							builder.setMessage("This note is not encrypted!")
									.setCancelable(false)
									.setNegativeButton(
											"Comfirm",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													dialog.cancel();
												}
											});
							AlertDialog alert = builder.create();
							alert.show();
						}

						else {
							// 这里添加的是判断是否在指定区域的函数
							// s是当前地理位置信息
							// theLocation是已指定区域
							SQLiteDatabase my_info_1 = SQLiteDatabase
									.openOrCreateDatabase(
											"/data/data/apple.encryptedNode/databases/password.db",
											null);
							Cursor cur = my_info_1.query("password", null,
									"fileName = '" + fileName1 + "'", null,
									null, null, null);
							cur.moveToFirst();
							String t1, t2, t3;
							t1 = cur.getString(cur.getColumnIndex("longitude"));
							t2 = cur.getString(cur.getColumnIndex("latitude"));
							t3 = cur.getString(cur.getColumnIndex("rrd"));
							String theLocation = null;
							theLocation = t1 + t2;
							double fort1 = Double.parseDouble(t1);
							double fort2 = Double.parseDouble(t2);
							double fors1 = Double.parseDouble(s1);
							double fors2 = Double.parseDouble(s2);
							double rrd = Double.parseDouble(t3);
							my_info_1.close();
							Log.e("cl", "save" + fors1 + fors2 + rrd);
							Log.e("cl", "get" + fort1 + fort2 + rrd);
							Log.e("cl", s);
							Log.e("cl", theLocation);
							// 这里添加的是获取对应文件的所取地理位置theLocation
							if (IsCorrect(Double.parseDouble(s1),
									Double.parseDouble(s2),
									Double.parseDouble(t1),
									Double.parseDouble(t2),
									Double.parseDouble(t3))) {
								// 解密部分
								s = theLocation;
								// 解密部分
								Dialog decryptionDialog = new Dialog(
										EncryptedNoteActivity.this);
								decryptionDialog
										.setContentView(R.layout.decryptiondialog);
								decryptionDialog.setTitle(" 请输入密码");
								Button dialogOperateButtonForDe = (Button) decryptionDialog
										.findViewById(R.id.dialogOperateButton2);
								dialogOperateButtonForDe.setText("解密");
								Button dialogCancelButtonForDe = (Button) decryptionDialog
										.findViewById(R.id.dialogCancelButton2);
								dialogCancelButtonForDe
										.setOnClickListener(new DialogDismiss(
												decryptionDialog));
								dialogOperateButtonForDe
										.setOnClickListener(new DialogDecryptionBtnEvent(
												decryptionDialog));
								decryptionDialog.show();
							} else {
								Toast.makeText(EncryptedNoteActivity.this,
										"对不起，你不在指定位置！ ", Toast.LENGTH_SHORT)
										.show();
							}
						}
						break;
					case 4:// send
						mCursor.moveToPosition(longSelectPosition);
						// int id1 = mCursor.getInt(0);
						String fileName2 = mCursor.getString(1);
						Log.e("adam",
								"fileName:" + fileName2
										+ fileName2.contains(" *encrypted*"));
						if (!fileName2.contains(" *encrypted*")) {
							Log.e("adam", "not Contains encrypted");
							AlertDialog.Builder builder = new AlertDialog.Builder(
									EncryptedNoteActivity.this);
							builder.setMessage("This note is not encrypted!")
									.setCancelable(false)
									.setNegativeButton(
											"Comfirm",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int id) {
													dialog.cancel();
												}
											});
							AlertDialog alert = builder.create();
							alert.show();
						} else {
							// 这里添加的是判断是否在指定区域的函数
							// s是当前地理位置信息
							// theLocation是已指定区域
							SQLiteDatabase my_info_1 = SQLiteDatabase
									.openOrCreateDatabase(
											"/data/data/apple.encryptedNode/databases/password.db",
											null);
							Cursor cur = my_info_1.query("password", null,
									"fileName = '" + fileName2 + "'", null,
									null, null, null);
							cur.moveToFirst();

							tlon = cur.getString(cur
									.getColumnIndex("longitude"));
							tlai = cur.getString(cur.getColumnIndex("latitude"));
							trrd = cur.getString(cur.getColumnIndex("rrd"));
							String theLocation = null;
							theLocation = tlon + tlai;
							my_info_1.close();
							Log.e("cl", "shit");
							// 这里添加的是获取对应文件的所取地理位置theLocation
							// 发送部分
							Dialog sendDialog = new Dialog(
									EncryptedNoteActivity.this);
							sendDialog.setContentView(R.layout.senddialog);
							sendDialog.setTitle(" 请输入号码");
							Button dialogOperateButtonForDe = (Button) sendDialog
									.findViewById(R.id.dialogOperateButton001);
							dialogOperateButtonForDe.setText("发送");
							Button dialogCancelButtonForDe = (Button) sendDialog
									.findViewById(R.id.dialogCancelButton002);
							dialogCancelButtonForDe
									.setOnClickListener(new DialogDismiss(
											sendDialog));
							dialogOperateButtonForDe
									.setOnClickListener(new DialogSendBtnEvent(
											sendDialog));
							sendDialog.show();

						}

						break;
					}

				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		}

	};

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);
		operationDAO = new OperationDAO(this);
		setContentView(R.layout.mainview);
		loc();// 获得坐标
		list();// 初始化list

	}

	public void onCreatex(Bundle savedInstanceState) {
		operationDAO = new OperationDAO(this);
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);
		setContentView(R.layout.mainview);

		// 获取解密密码
		LocationManager lm = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// 定义Criteria对象
		Criteria criteria = new Criteria();
		// 设置定位精确度 Criteria.ACCURACY_COARSE 比较粗略， Criteria.ACCURACY_FINE则比较精细
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		// 设置是否需要海拔信息 Altitude
		criteria.setAltitudeRequired(true);
		// 设置是否需要方位信息 Bearing
		criteria.setBearingRequired(true);
		// 设置是否允许运营商收费
		criteria.setCostAllowed(true);
		// 设置对电源的需求
		criteria.setPowerRequirement(Criteria.POWER_LOW);

		// 获取GPS信息提供者
		String bestProvider = lm.getBestProvider(criteria, true);

		// 获取定位信息
		Location location;
		location = lm.getLastKnownLocation(bestProvider);
		double longitude = 0;
		double latitude = 0;
		if (location != null) {
			longitude = (double) (location.getLongitude());
			latitude = (double) (location.getLatitude());
		}

		// 位置监听器
		LocationListener locationListener = new LocationListener() {

			// 当位置改变时触发
			public void onLocationChanged(Location location) {
				Log.i("yao", location.toString());
			}

			// Provider失效时触发
			public void onProviderDisabled(String arg0) {
				Log.i("yao", arg0);

			}

			// Provider可用时触发
			public void onProviderEnabled(String arg0) {
				Log.i("yao", arg0);
			}

			// Provider状态改变时触发
			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
				Log.i("yao", "onStatusChanged");
			}
		};
		// 500毫秒更新一次，忽略位置变化
		lm.requestLocationUpdates(bestProvider, 500, 0, locationListener);

		// s1 = String.valueOf(longitude);
		// s2 = String.valueOf(latitude);
		s1 = String.format("%.4f", longitude);
		s2 = String.format("%.4f", latitude);
		s = s1 + s2;

		/*
		 * ArrayList<HashMap<String,String>> list = new
		 * ArrayList<HashMap<String,String>>(); HashMap<String, String> map1 =
		 * new HashMap<String, String>(); map1.put("textView1", "sdfsdfsdf");
		 * HashMap<String, String> map2 = new HashMap<String, String>();
		 * map2.put("textView1", "appleappleapple"); list.add(map1);
		 * list.add(map2);
		 * 
		 * SimpleAdapter listAdapter = new
		 * SimpleAdapter(this,list,R.layout.note_list_component, new
		 * String[]{"textView1"}, new int[]{R.id.topicName});
		 * setListAdapter(listAdapter);
		 */

		// mCursor = this.getContentResolver().query(People.CONTENT_URI, null,
		// null, null, null);
		firstClickTime = new Long(0);
		mCursor = this.operationDAO.query();
		startManagingCursor(mCursor);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
		// android.R.layout.two_line_list_item,
				R.layout.note_list_component, mCursor,
				// new String[] {People.NAME},
				new String[] { EncryptedNodeOpenHelper.KEY_NAME,
						EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
						R.id.topicName, R.id.topicContent });
		adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

			public boolean setViewValue(View view, Cursor cursor,
					int columnIndex) {
				System.out.println(view.toString());
				System.out.println("adam~" + "columnIndex:" + columnIndex
						+ ((TextView) view).getText().toString());
				return false;
			}
		});
		setListAdapter(adapter);
		// getListView().;
		ImageView image = (ImageView) getListView().getAdapter()
				.getView(1, null, getListView())
				.findViewById(R.id.encryptionStatus);
		image.setImageResource(R.drawable.notepad);

		TextView textView = (TextView) getListView().getAdapter()
				.getView(1, null, getListView()).findViewById(R.id.topicName);
		textView.setText("adamadamadam");
		// setListAdapter(adapter);
		adapter.notifyDataSetChanged();
		// adapter.
		// ((SimpleAdapter) adapter).notifyViewChanaged();
		// getListView().draw(this.getc);
		// image.refreshDrawableState();
		Log.e("adam", "textView.getText: " + textView.getText());
		Log.e("adam",
				""
						+ getListView().getAdapter()
								.getView(0, null, getListView())
								.findViewById(R.id.noteListComponentIcon));
		Log.e("adam",
				"listViewChildren: "
						+ (getListView().getAdapter().getView(0, null,
								getListView())
								.findViewById(R.id.encryptionStatus)));
		// ImageView image =
		// ((ImageView)(getListView().getChildAt(0).findViewById(R.id.encryptionStatus)));
		// image.setImageResource(R.drawable.notepad);
		// ListView listView = new ListView(this);

		// newNoteButton = (Button) findViewById(R.id.newNoteButton);
		/*
		 * newNoteButton.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View arg0) { Intent
		 * newNoteActivityIntent = new Intent();
		 * newNoteActivityIntent.setClass(EncryptedNoteActivity.this,
		 * NewNoteActivity.class);
		 * EncryptedNoteActivity.this.startActivity(newNoteActivityIntent); }
		 * });
		 */
		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				longSelectPosition = arg2;
				final CharSequence[] items = { getString(R.string.open),
						getString(R.string.delete),
						getString(R.string.encrypt),
						getString(R.string.decrypt), getString(R.string.send) };
				AlertDialog.Builder builder = new AlertDialog.Builder(
						EncryptedNoteActivity.this);
				builder.setTitle("Operations");
				builder.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						switch (item) {
						case 0:// open
							if (longSelectPosition > -1) {
								mCursor.moveToPosition(longSelectPosition);
								int keyId = mCursor.getInt(0);
								String keyName = mCursor.getString(1);
								String keyContent = mCursor.getString(2);
								longSelectPosition = -1;
								showNewNoteActivity(keyId, keyName, keyContent);
							}
							break;
						case 1:// delete
							if (longSelectPosition > -1) {
								mCursor.moveToPosition(longSelectPosition);
								int id = mCursor.getInt(0);
								String fileName = mCursor.getString(1);
								if (fileName.contains(" *encrypted*")) {
									Log.e("adam", "Contains encrypted");
									AlertDialog.Builder builder = new AlertDialog.Builder(
											EncryptedNoteActivity.this);
									builder.setMessage(
											"Please decrypt this note first!")
											.setCancelable(false)
											.setNegativeButton(
													"Comfirm",
													new DialogInterface.OnClickListener() {
														public void onClick(
																DialogInterface dialog,
																int id) {
															dialog.cancel();
														}
													});
									AlertDialog alert = builder.create();
									alert.show();
								} else {
									longSelectPosition = -1;
									operationDAO.delete(id);
									// mCursor = operationDAO.query();
									mCursor.requery();
									startManagingCursor(mCursor);
									EncryptedNoteActivity.this.getListView()
											.clearDisappearingChildren();
								}
							}

							break;
						case 2:// encrypt
							mCursor.moveToPosition(longSelectPosition);
							// int id = mCursor.getInt(0);
							String fileName = mCursor.getString(1);
							if (fileName.contains(" *encrypted*")) {
								Log.e("adam", "Contains encrypted");
								AlertDialog.Builder builder = new AlertDialog.Builder(
										EncryptedNoteActivity.this);
								builder.setMessage(
										"This note is already encrypted!")
										.setCancelable(false)
										.setNegativeButton(
												"Comfirm",
												new DialogInterface.OnClickListener() {
													public void onClick(
															DialogInterface dialog,
															int id) {
														dialog.cancel();
													}
												});
								AlertDialog alert = builder.create();
								alert.show();
							} else {
								Dialog encryptionDialog = new Dialog(
										EncryptedNoteActivity.this);
								encryptionDialog
										.setContentView(R.layout.encryptiondialog);
								encryptionDialog.setTitle("请核对信息无误!");
								Button dialogOperateButton = (Button) encryptionDialog
										.findViewById(R.id.dialogOperateButton);
								dialogOperateButton.setText("加密");
								Button dialogCancelButton = (Button) encryptionDialog
										.findViewById(R.id.dialogCancelButton);
								dialogCancelButton
										.setOnClickListener(new DialogDismiss(
												encryptionDialog));
								dialogOperateButton
										.setOnClickListener(new DialogEncryptionBtnEvent(
												encryptionDialog));

								encryptionDialog.show();
							}
							break;
						case 3:// decrypt
							mCursor.moveToPosition(longSelectPosition);
							// int id1 = mCursor.getInt(0);
							String fileName1 = mCursor.getString(1);
							Log.e("adam",
									"fileName:"
											+ fileName1
											+ fileName1
													.contains(" *encrypted*"));
							if (!fileName1.contains(" *encrypted*")) {
								Log.e("adam", "not Contains encrypted");
								AlertDialog.Builder builder = new AlertDialog.Builder(
										EncryptedNoteActivity.this);
								builder.setMessage(
										"This note is not encrypted!")
										.setCancelable(false)
										.setNegativeButton(
												"Comfirm",
												new DialogInterface.OnClickListener() {
													public void onClick(
															DialogInterface dialog,
															int id) {
														dialog.cancel();
													}
												});
								AlertDialog alert = builder.create();
								alert.show();
							}

							else {
								// 这里添加的是判断是否在指定区域的函数
								// s是当前地理位置信息
								// theLocation是已指定区域
								SQLiteDatabase my_info_1 = SQLiteDatabase
										.openOrCreateDatabase(
												"/data/data/apple.encryptedNode/databases/password.db",
												null);
								Cursor cur = my_info_1.query("password", null,
										"fileName = '" + fileName1 + "'", null,
										null, null, null);
								cur.moveToFirst();
								String t1, t2, t3;
								t1 = cur.getString(cur
										.getColumnIndex("longitude"));
								t2 = cur.getString(cur
										.getColumnIndex("latitude"));
								t3 = cur.getString(cur.getColumnIndex("rrd"));
								String theLocation = null;
								theLocation = t1 + t2;
								double fort1 = Double.parseDouble(t1);
								double fort2 = Double.parseDouble(t2);
								double fors1 = Double.parseDouble(s1);
								double fors2 = Double.parseDouble(s2);
								double rrd = Double.parseDouble(t3);
								my_info_1.close();
								Log.e("cl", "save" + fors1 + fors2 + rrd);
								Log.e("cl", "get" + fort1 + fort2 + rrd);
								Log.e("cl", s);
								Log.e("cl", theLocation);
								// 这里添加的是获取对应文件的所取地理位置theLocation
								if (IsCorrect(Double.parseDouble(s1),
										Double.parseDouble(s2),
										Double.parseDouble(t1),
										Double.parseDouble(t2),
										Double.parseDouble(t3))) {
									// 解密部分
									s = theLocation;
									// 解密部分
									Dialog decryptionDialog = new Dialog(
											EncryptedNoteActivity.this);
									decryptionDialog
											.setContentView(R.layout.decryptiondialog);
									decryptionDialog.setTitle(" 请输入密码");
									Button dialogOperateButtonForDe = (Button) decryptionDialog
											.findViewById(R.id.dialogOperateButton2);
									dialogOperateButtonForDe.setText("解密");
									Button dialogCancelButtonForDe = (Button) decryptionDialog
											.findViewById(R.id.dialogCancelButton2);
									dialogCancelButtonForDe
											.setOnClickListener(new DialogDismiss(
													decryptionDialog));
									dialogOperateButtonForDe
											.setOnClickListener(new DialogDecryptionBtnEvent(
													decryptionDialog));
									decryptionDialog.show();
								} else {
									Toast.makeText(EncryptedNoteActivity.this,
											"对不起，你不在指定位置！ ", Toast.LENGTH_SHORT)
											.show();
								}
							}
							break;
						case 4:// send
							mCursor.moveToPosition(longSelectPosition);
							// int id1 = mCursor.getInt(0);
							String fileName2 = mCursor.getString(1);
							Log.e("adam",
									"fileName:"
											+ fileName2
											+ fileName2
													.contains(" *encrypted*"));
							if (!fileName2.contains(" *encrypted*")) {
								Log.e("adam", "not Contains encrypted");
								AlertDialog.Builder builder = new AlertDialog.Builder(
										EncryptedNoteActivity.this);
								builder.setMessage(
										"This note is not encrypted!")
										.setCancelable(false)
										.setNegativeButton(
												"Comfirm",
												new DialogInterface.OnClickListener() {
													public void onClick(
															DialogInterface dialog,
															int id) {
														dialog.cancel();
													}
												});
								AlertDialog alert = builder.create();
								alert.show();
							} else {
								// 这里添加的是判断是否在指定区域的函数
								// s是当前地理位置信息
								// theLocation是已指定区域
								SQLiteDatabase my_info_1 = SQLiteDatabase
										.openOrCreateDatabase(
												"/data/data/apple.encryptedNode/databases/password.db",
												null);
								Cursor cur = my_info_1.query("password", null,
										"fileName = '" + fileName2 + "'", null,
										null, null, null);
								cur.moveToFirst();

								tlon = cur.getString(cur
										.getColumnIndex("longitude"));
								tlai = cur.getString(cur
										.getColumnIndex("latitude"));
								trrd = cur.getString(cur.getColumnIndex("rrd"));
								String theLocation = null;
								theLocation = tlon + tlai;
								my_info_1.close();
								Log.e("cl", "shit");
								// 这里添加的是获取对应文件的所取地理位置theLocation
								// 发送部分
								Dialog sendDialog = new Dialog(
										EncryptedNoteActivity.this);
								sendDialog.setContentView(R.layout.senddialog);
								sendDialog.setTitle(" 请输入号码");
								Button dialogOperateButtonForDe = (Button) sendDialog
										.findViewById(R.id.dialogOperateButton001);
								dialogOperateButtonForDe.setText("发送");
								Button dialogCancelButtonForDe = (Button) sendDialog
										.findViewById(R.id.dialogCancelButton002);
								dialogCancelButtonForDe
										.setOnClickListener(new DialogDismiss(
												sendDialog));
								dialogOperateButtonForDe
										.setOnClickListener(new DialogSendBtnEvent(
												sendDialog));
								sendDialog.show();

							}

							break;
						}

					}
				});
				AlertDialog alert = builder.create();
				alert.show();
				return true;
			}

		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.encryptednoteactivitymenu, menu);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_open:
			// EncryptedNoteActivity.this.
			int position = EncryptedNoteActivity.this.getSelectedItemPosition();
			Log.e("adam", "position: " + position);
			Toast.makeText(EncryptedNoteActivity.this, "position: " + position,
					Toast.LENGTH_SHORT).show();
			if (position > -1) {
				mCursor.moveToPosition(position);
				int keyId = mCursor.getInt(0);
				String keyName = mCursor.getString(1);
				String keyContent = mCursor.getString(2);
				showNewNoteActivity(keyId, keyName, keyContent);
			}
			Toast.makeText(EncryptedNoteActivity.this, "menu_open",
					Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_new:
			showNewNoteActivity(-1, null, null);
			return true;
		case R.id.menu_delete:
			Toast.makeText(EncryptedNoteActivity.this, "menu_delete",
					Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_config:
			Toast.makeText(EncryptedNoteActivity.this, "menu_config",
					Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_about:
			Toast.makeText(EncryptedNoteActivity.this, "menu_about",
					Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_exit:
			Toast.makeText(EncryptedNoteActivity.this, "menu_exit",
					Toast.LENGTH_SHORT).show();
			EncryptedNoteActivity.this.finish();
			return true;
		}
		return false;
	}

	// it will fired when we click one record in listView.
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.e("Adam", "itemClick");
		Long currentClickTime = new Date().getTime();
		// act as a double click and then show the NewNoteActivity.
		if (currentClickTime - firstClickTime < 1100) {
			currentClickTime = new Long(0);
			mCursor.moveToPosition(position);
			int keyId = mCursor.getInt(0);
			String keyName = mCursor.getString(1);
			String keyContent = mCursor.getString(2);
			showNewNoteActivity(keyId, keyName, keyContent);
			Toast.makeText(EncryptedNoteActivity.this, "doubleClick",
					Toast.LENGTH_SHORT).show();

		} else {
			/*
			 * ListView lv = null; lv.getch
			 */
			// l.setSelection(position);
			l.setSelected(true);

			// l.setSelector(position);
			// l.getChildAt(position).setSelected(true);

		}
		firstClickTime = currentClickTime;

	}

	@Override
	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		Toast.makeText(EncryptedNoteActivity.this,
				"keyPressed: " + event.describeContents(), Toast.LENGTH_SHORT)
				.show();
		return super.onKeyLongPress(keyCode, event);
	}

	public void showNewNoteActivity(int keyId, String keyName, String keyContent) {
		Intent newNoteActivityIntent = new Intent();
		if (keyName != null || keyContent != null) {
			newNoteActivityIntent.putExtra("keyId", keyId);
			newNoteActivityIntent.putExtra("keyName", keyName);
			newNoteActivityIntent.putExtra("keyContent", keyContent);
		}
		newNoteActivityIntent.setClass(EncryptedNoteActivity.this,
				NewNoteActivity.class);
		EncryptedNoteActivity.this.startActivity(newNoteActivityIntent);
	}

	@Override
	protected void onResume() {

		mCursor = this.operationDAO.query();
		startManagingCursor(mCursor);
		ListAdapter adapter = new SimpleCursorAdapter(this,
		// android.R.layout.two_line_list_item,
				R.layout.note_list_component, mCursor,
				// new String[] {People.NAME},
				new String[] { EncryptedNodeOpenHelper.KEY_NAME,
						EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
						R.id.topicName, R.id.topicContent });
		setListAdapter(adapter);

		super.onResume();
	}

	@Override
	protected void onPause() {
		mCursor = this.operationDAO.query();
		startManagingCursor(mCursor);
		ListAdapter adapter = new SimpleCursorAdapter(this,
		// android.R.layout.two_line_list_item,
				R.layout.note_list_component, mCursor,
				// new String[] {People.NAME},
				new String[] { EncryptedNodeOpenHelper.KEY_NAME,
						EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
						R.id.topicName, R.id.topicContent });
		setListAdapter(adapter);
		super.onPause();
	}

	// 如何判断一个文件是否存在

	public boolean fileIsExists(String filename) {
		try {
			File f = new File(filename);
			if (!f.exists()) {
				return false;
			}

		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		return true;
	}

	private class DialogEncryptionBtnEvent implements OnClickListener {

		private Dialog encryptionDialog;

		public DialogEncryptionBtnEvent(Dialog encryptionDialog) {
			this.encryptionDialog = encryptionDialog;
		}

		public void onClick(View arg0) {
			Log.e("dsa", "dsadsadsa");
			mCursor.moveToPosition(longSelectPosition);
			int id = mCursor.getInt(0);
			String fileName = mCursor.getString(1);
			String fileContent = mCursor.getString(2);
			Log.e("dsa", "dsadsadsa");
			// 这里就是获取到了加密密码
			String t1 = ((EditText) encryptionDialog
					.findViewById(R.id.EditText02)).getText().toString();
			String t2 = ((EditText) encryptionDialog
					.findViewById(R.id.EditText01)).getText().toString();
			String t3 = ((EditText) encryptionDialog
					.findViewById(R.id.EditText03)).getText().toString();
			String t4 = ((EditText) encryptionDialog
					.findViewById(R.id.EditText04)).getText().toString();
			String keyData = sha1(t1 + t2 + t3);
			SQLiteDatabase my_info_0 = null;
			if (!fileIsExists("/data/data/apple.encryptedNode/databases/password.db")) {
				my_info_0 = SQLiteDatabase.openOrCreateDatabase(
						"/data/data/apple.encryptedNode/databases/password.db",
						null);
				my_info_0
						.execSQL("create table password('fileName','longitude','latitude','password','rrd')");
			} else {
				my_info_0 = SQLiteDatabase.openOrCreateDatabase(
						"/data/data/apple.encryptedNode/databases/password.db",
						null);
			}
			Log.e("dsa", "dsadsadsa");
			my_info_0
					.execSQL("insert into password(fileName,longitude,latitude,password,rrd) values('"
							+ fileName
							+ " *encrypted*"
							+ "','"
							+ t1
							+ "','"
							+ t2 + "','" + t3 + "','" + t4 + "')");
			my_info_0.close();

			// t1经度，t2纬度，t3是用户密码
			// operationDAO.delete(id);
			Log.e("adam", "encryptedkeyData:" + keyData);
			Log.e("adam", "dialog.onclick");
			try {
				EncryptTool encryptTool = new EncryptTool();
				fileContent = encryptTool.encrypt(keyData, fileContent);
				fileName = fileName + " *encrypted*";
				operationDAO.update(id, fileName, fileContent);
				Toast.makeText(EncryptedNoteActivity.this,
						"encrypted successfully ", Toast.LENGTH_SHORT).show();
			} catch (InvalidKeyException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			} catch (IllegalBlockSizeException e) {
				e.printStackTrace();
			} catch (BadPaddingException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			// encryptTool.encrypt(keyData, str);
			mCursor = operationDAO.query();
			// mCursor.requery();
			startManagingCursor(mCursor);
			ListAdapter adapter = new SimpleCursorAdapter(
					EncryptedNoteActivity.this,
					// android.R.layout.two_line_list_item,
					R.layout.note_list_component, mCursor,
					// new String[] {People.NAME},
					new String[] { EncryptedNodeOpenHelper.KEY_NAME,
							EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
							R.id.topicName, R.id.topicContent });
			setListAdapter(adapter);
			encryptionDialog.dismiss();
		}
	}

	private class DialogDismiss implements OnClickListener {
		private Dialog dialog;

		public DialogDismiss(Dialog dialog) {
			this.dialog = dialog;
		}

		public void onClick(View v) {
			this.dialog.dismiss();
		}

	}

	private class DialogDecryptionBtnEvent implements OnClickListener {
		private Dialog dncryptionDialog;

		public DialogDecryptionBtnEvent(Dialog dncryptionDialog) {
			this.dncryptionDialog = dncryptionDialog;
		}

		public void onClick(View v) {
			mCursor.moveToPosition(longSelectPosition);
			int id = mCursor.getInt(0);
			String fileName = mCursor.getString(1);
			Log.e("adam",
					"fileName:" + fileName + fileName.contains(" *encrypted*"));
			if (!fileName.contains(" *encrypted*")) {
				Log.e("adam", "not Contains encrypted");
				AlertDialog.Builder builder = new AlertDialog.Builder(
						EncryptedNoteActivity.this);
				builder.setMessage("This note is not encrypted!")
						.setCancelable(false)
						.setNegativeButton("Comfirm",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
				return;
			}
			String fileContent = mCursor.getString(2);
			String password = ((EditText) dncryptionDialog
					.findViewById(R.id.DeditText1)).getText().toString();
			String keyData = sha1(s + password);

			// operationDAO.delete(id);
			Log.e("adam", "decryptedkeyData:" + keyData);
			Log.e("adam", "dialog.onclick");

			try {
				EncryptTool encryptTool = new EncryptTool();

				fileContent = encryptTool.decrypt(keyData, fileContent);
				fileName = fileName.replace(" *encrypted*", "");
				operationDAO.update(id, fileName, fileContent);
				Toast.makeText(EncryptedNoteActivity.this,
						"decrypted successfully ", Toast.LENGTH_SHORT).show();
				mCursor.moveToPosition(longSelectPosition);
				// int id1 = mCursor.getInt(0);
				String fileName1 = mCursor.getString(1);
				SQLiteDatabase my_info_1 = SQLiteDatabase.openOrCreateDatabase(
						"/data/data/apple.encryptedNode/databases/password.db",
						null);
				my_info_1.execSQL("delete from password where fileName = '"
						+ fileName1 + "'");
				my_info_1.close();
			} catch (InvalidKeyException e) {
				Toast.makeText(EncryptedNoteActivity.this,
						"InvalidKeyException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				Toast.makeText(EncryptedNoteActivity.this,
						"NoSuchAlgorithmException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				Toast.makeText(EncryptedNoteActivity.this,
						"NoSuchPaddingException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (IllegalBlockSizeException e) {
				Toast.makeText(EncryptedNoteActivity.this,
						"IllegalBlockSizeException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (BadPaddingException e) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						EncryptedNoteActivity.this);
				builder.setMessage("The Password is not correct!")
						.setCancelable(false)
						.setNegativeButton("Comfirm",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
				// e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				Toast.makeText(EncryptedNoteActivity.this,
						"InvalidKeySpecException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (IOException e) {
				Toast.makeText(EncryptedNoteActivity.this, "IOException",
						Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			}

			// encryptTool.encrypt(keyData, str);
			mCursor = operationDAO.query();
			// mCursor.requery();
			startManagingCursor(mCursor);
			ListAdapter adapter = new SimpleCursorAdapter(
					EncryptedNoteActivity.this,
					// android.R.layout.two_line_list_item,
					R.layout.note_list_component, mCursor,
					// new String[] {People.NAME},
					new String[] { EncryptedNodeOpenHelper.KEY_NAME,
							EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
							R.id.topicName, R.id.topicContent });
			setListAdapter(adapter);
			dncryptionDialog.dismiss();
		}

		private LocationManager getSystemService(String locationService) {
			// TODO Auto-generated method stub
			return null;
		}
	}

	public class DialogSendBtnEvent implements OnClickListener {
		private Dialog sendDialog;

		public DialogSendBtnEvent(Dialog sendDialog) {
			this.sendDialog = sendDialog;
		}

		public void onClick(View v) {
			mCursor.moveToPosition(longSelectPosition);
			int id = mCursor.getInt(0);
			String fileName = mCursor.getString(1);
			Log.e("adam",
					"fileName:" + fileName + fileName.contains(" *encrypted*"));
			if (!fileName.contains(" *encrypted*")) {
				Log.e("adam", "not Contains encrypted");
				AlertDialog.Builder builder = new AlertDialog.Builder(
						EncryptedNoteActivity.this);
				builder.setMessage("This note is not encrypted!")
						.setCancelable(false)
						.setNegativeButton("Comfirm",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
				return;
			}
			// 文件内容
			String fileContent = mCursor.getString(2);
			String phoneNumber = ((EditText) sendDialog
					.findViewById(R.id.sendEditText1)).getText().toString();
			String pkt = null;// 数据报报头
			pkt = tlon + "@" + tlai + "@" + trrd;

			Log.e("cl", pkt);
			Log.e("cl", fileContent);
			String MsgStr = pkt + "@" + fileContent;

			// sma bytes style
			byte[] bytes = fileContent.getBytes();
			SmsManager sms = SmsManager.getDefault();/* 建立短信发送管理对象 */
			try {
				short pt = 80; /* 设置端口号 */
				// PendingIntent pi = PendingIntent.getBroadcast(this, 0, new
				// Intent(), 0);
				sms.sendDataMessage(phoneNumber, null, pt, bytes, null, null); /*
																				 * 填写接收号码
																				 * 、
																				 * 短信数据等参数
																				 * ，
																				 * 并发送短信
																				 */
				// Toast.makeText(this,"发送成功",Toast.LENGTH_LONG).show ();
				Log.e("adam", "sended");
			} catch (Exception e) {
				Log.e("adam", "unsended");
				// Toast.makeText(this, "发送失败\n"+e.getMessage(),Toast.
				// LENGTH_LONG).show();
			} //

			mCursor = operationDAO.query();
			// mCursor.requery();
			startManagingCursor(mCursor);
			ListAdapter adapter = new SimpleCursorAdapter(
					EncryptedNoteActivity.this,
					// android.R.layout.two_line_list_item,
					R.layout.note_list_component, mCursor,
					// new String[] {People.NAME},
					new String[] { EncryptedNodeOpenHelper.KEY_NAME,
							EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
							R.id.topicName, R.id.topicContent });
			setListAdapter(adapter);
			sendDialog.dismiss();
		}

		private LocationManager getSystemService(String locationService) {
			// TODO Auto-generated method stub
			return null;
		}
	}

	@Override
	protected void onDestroy() {
		// operationDAO.close();
		super.onDestroy();
	}

}
